package br.com.educa.controle;

import br.com.educa.modelo.academico.Alunos;
import br.com.educa.modelo.academico.AlunosTurmas;
import br.com.educa.modelo.academico.Turmas;
import br.com.educa.modelo.academico.enumerator.SituacaoAluno;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.joda.time.format.DateTimeFormat;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.roo.addon.web.mvc.controller.json.RooWebJson;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

@RooWebJson(jsonObject = AlunosTurmas.class)
@Controller
@RequestMapping("/alunosturmases")
@RooWebScaffold(path = "alunosturmases", formBackingObject = AlunosTurmas.class)
public class AlunosTurmasController {

    @RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid AlunosTurmas alunosTurmas, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, alunosTurmas);
            return "alunosturmases/create";
        }
        uiModel.asMap().clear();
        alunosTurmas.persist();
        return "redirect:/alunosturmases/" + encodeUrlPathSegment(alunosTurmas.getId().toString(), httpServletRequest);
    }

    @RequestMapping(params = "form", produces = "text/html")
    public String createForm(Model uiModel) {
        populateEditForm(uiModel, new AlunosTurmas());
        return "alunosturmases/create";
    }

    @RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable("id") Long id, Model uiModel) {
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("alunosturmas", AlunosTurmas.findAlunosTurmas(id));
        uiModel.addAttribute("itemId", id);
        return "alunosturmases/show";
    }

    @RequestMapping(produces = "text/html")
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            uiModel.addAttribute("alunosturmases", AlunosTurmas.findAlunosTurmasEntries(firstResult, sizeNo));
            float nrOfPages = (float) AlunosTurmas.countAlunosTurmases() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("alunosturmases", AlunosTurmas.findAllAlunosTurmases());
        }
        addDateTimeFormatPatterns(uiModel);
        return "alunosturmases/list";
    }

    @RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid AlunosTurmas alunosTurmas, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, alunosTurmas);
            return "alunosturmases/update";
        }
        uiModel.asMap().clear();
        alunosTurmas.merge();
        return "redirect:/alunosturmases/" + encodeUrlPathSegment(alunosTurmas.getId().toString(), httpServletRequest);
    }

    @RequestMapping(value = "/{id}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable("id") Long id, Model uiModel) {
        populateEditForm(uiModel, AlunosTurmas.findAlunosTurmas(id));
        return "alunosturmases/update";
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        AlunosTurmas alunosTurmas = AlunosTurmas.findAlunosTurmas(id);
        alunosTurmas.remove();
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/alunosturmases";
    }

    void addDateTimeFormatPatterns(Model uiModel) {
        uiModel.addAttribute("alunosTurmas_datamatricula_date_format", DateTimeFormat.patternForStyle("M-", LocaleContextHolder.getLocale()));
    }

    void populateEditForm(Model uiModel, AlunosTurmas alunosTurmas) {
        uiModel.addAttribute("alunosTurmas", alunosTurmas);
        addDateTimeFormatPatterns(uiModel);
        uiModel.addAttribute("situacaoalunoes", Arrays.asList(SituacaoAluno.values()));
    }

    String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {
        }
        return pathSegment;
    }

    @RequestMapping(value = "/{id}", headers = "Accept=application/json")
    @ResponseBody
    public ResponseEntity<java.lang.String> showJson(@PathVariable("id") Long id) {
        AlunosTurmas alunosTurmas = AlunosTurmas.findAlunosTurmas(id);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        if (alunosTurmas == null) {
            return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<String>(alunosTurmas.toJson(), headers, HttpStatus.OK);
    }

    @RequestMapping(headers = "Accept=application/json")
    @ResponseBody
    public ResponseEntity<java.lang.String> listJson() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        List<AlunosTurmas> result = AlunosTurmas.findAllAlunosTurmases();
        return new ResponseEntity<String>(AlunosTurmas.toJsonArray(result), headers, HttpStatus.OK);
    }

    @RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
    public ResponseEntity<java.lang.String> createFromJson(@RequestBody String json) {
        AlunosTurmas alunosTurmas = AlunosTurmas.fromJsonToAlunosTurmas(json);
        alunosTurmas.persist();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        return new ResponseEntity<String>(headers, HttpStatus.CREATED);
    }

    @RequestMapping(value = "/jsonArray", method = RequestMethod.POST, headers = "Accept=application/json")
    public ResponseEntity<java.lang.String> createFromJsonArray(@RequestBody String json) {
        for (AlunosTurmas alunosTurmas : AlunosTurmas.fromJsonArrayToAlunosTurmases(json)) {
            alunosTurmas.persist();
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        return new ResponseEntity<String>(headers, HttpStatus.CREATED);
    }

    @RequestMapping(method = RequestMethod.PUT, headers = "Accept=application/json")
    public ResponseEntity<java.lang.String> updateFromJson(@RequestBody String json) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        AlunosTurmas alunosTurmas = AlunosTurmas.fromJsonToAlunosTurmas(json);
        if (alunosTurmas.merge() == null) {
            return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity<String>(headers, HttpStatus.OK);
    }

    @RequestMapping(value = "/jsonArray", method = RequestMethod.PUT, headers = "Accept=application/json")
    public ResponseEntity<java.lang.String> updateFromJsonArray(@RequestBody String json) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        for (AlunosTurmas alunosTurmas : AlunosTurmas.fromJsonArrayToAlunosTurmases(json)) {
            if (alunosTurmas.merge() == null) {
                return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
            }
        }
        return new ResponseEntity<String>(headers, HttpStatus.OK);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, headers = "Accept=application/json")
    public ResponseEntity<java.lang.String> deleteFromJson(@PathVariable("id") Long id) {
        AlunosTurmas alunosTurmas = AlunosTurmas.findAlunosTurmas(id);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        if (alunosTurmas == null) {
            return new ResponseEntity<String>(headers, HttpStatus.NOT_FOUND);
        }
        alunosTurmas.remove();
        return new ResponseEntity<String>(headers, HttpStatus.OK);
    }

    @RequestMapping(params = "find=ByAnoEquals", headers = "Accept=application/json")
    @ResponseBody
    public ResponseEntity<java.lang.String> jsonFindAlunosTurmasesByAnoEquals(@RequestParam("ano") Integer ano) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        return new ResponseEntity<String>(AlunosTurmas.toJsonArray(AlunosTurmas.findAlunosTurmasesByAnoEquals(ano).getResultList()), headers, HttpStatus.OK);
    }

    @RequestMapping(params = "find=ByTurma", headers = "Accept=application/json")
    @ResponseBody
    public ResponseEntity<java.lang.String> jsonFindAlunosTurmasesByTurma(@RequestParam("turma") Turmas turma) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        return new ResponseEntity<String>(AlunosTurmas.toJsonArray(AlunosTurmas.findAlunosTurmasesByTurma(turma).getResultList()), headers, HttpStatus.OK);
    }

    @RequestMapping(params = "find=ByAluno", headers = "Accept=application/json")
    @ResponseBody
    public ResponseEntity<java.lang.String> jsonFindAlunosTurmasesByAluno(@RequestParam("aluno") Alunos aluno) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json; charset=utf-8");
        return new ResponseEntity<String>(AlunosTurmas.toJsonArray(AlunosTurmas.findAlunosTurmasesByAluno(aluno).getResultList()), headers, HttpStatus.OK);
    }
}
